import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store/index";

const request = axios.create({
    baseURL: `${process.env.VUE_APP_API}/api`,
    timeout: "2000",
});

// 配置请求拦截器
request.interceptors.request.use((config) => {
    NProgress.start();
    const userTempId = store.state.user.userTempId;
    config.headers.userTempId = userTempId;
    const token = localStorage.getItem("token");
    config.headers.token = token;
    return config;
});

// 配置响应拦截器
request.interceptors.response.use(
    (response) => {
        NProgress.done();
        if (response.data.code === 200) {
            return response.data.data;
        }
        return Promise.reject({
            message: response.data.message,
        });
    },
    (error) => {
        NProgress.done();
        return Promise.reject(error);
    },
);

export default request;
